package com.face.controller;

import com.face.common.Page;
import com.face.common.Result;
import com.face.common.ResultCode;
import com.face.entity.Account;
import com.face.entity.Role;
import com.face.exception.RoleExistException;
import com.face.service.AccountService;
import com.face.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private AccountService accountService;

    @GetMapping("/list")
    public Result list(@RequestParam(name = "shopId") String shopId, @RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                       @RequestParam(name = "limit", required = false, defaultValue = "10") Integer limit,
                       @RequestParam(name = "name", required = false) String name, @RequestParam(name = "status", required = false) Integer status){
        Page<Role> resultPage = roleService.findPage(shopId, name, status, page, limit);
        return Result.success(resultPage);
    }

    @PostMapping
    public Result save(@RequestBody Role role) {
        try {
            roleService.save(role);
        } catch (RoleExistException e) {
            return Result.failure(ResultCode.ROLE_EXIST);
        }
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        Role role = roleService.findById(id);
        return Result.success(role);
    }

    @PutMapping
    public Result update(@RequestBody Role role) {
        roleService.update(role);
        return Result.success();
    }

    @PatchMapping("/{id}/{status}")
    public Result updateStatus(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
        if (status == 1) {
            List<Account> accountList = accountService.findByRoleId(id);
            if (accountList.size() > 0) {
                return Result.failure(ResultCode.USER_EXISTS_UNDER_THIS_ROLE);
            }
        }
        roleService.updateStatus(id, status);
        return Result.success();
    }

    @GetMapping("/roleList")
    public Result roleList(@RequestParam(name = "shopId") String shopId){
        Page<Role> resultPage = roleService.findPage(shopId, "", 0, 1, 10000);
        return Result.success(resultPage);
    }
}
